// 引入接口文件
import { getMember, queryAllAddress, delBuilding, shareImg, downloadQrcode, qrcodeType, qrcodeCreate, homeRecommendCreate } from './baseinfoServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import { download } from '../../../../../utils/util.js';
//打包文件到压缩包
// import JSZip from 'jszip';
// import saveAs from 'file-saver';
// import $ from 'jquery';

// import toZip from 'utils/jszip'

// import toZip from '../../../../../utils/jszip'


// 初始默认状态
const defultState = {
        loading: false,
        btnLoading: false,
        biz: {
            queryForm: {}
        },
        areaList: [],
        currentImg: '',
        currentItem: {},
        productId: '',
        qrcodeCount: '',
        codeId: '',
        channelId: '',
        channelType: [],
        zysqList: [],
        showAdv: null,
        zysqUrl: `subPackages\/pages\/buildingDetail\/buildingDetail`
    }
    // 声明module
const tmpModule = {
    namespace: 'baseinfoModel',
    state: cloneDeep(defultState),
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                if ('' + tmpModule.pathname === '' + pathname) {
                    dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
                    dispatch({ type: 'getAreaList', payload: {} });
                    dispatch({ type: 'qrcodeType', payload: {} });
                    dispatch({ type: 'qrcodeType', payload: { isNull: '1' } });
                }
            })
        },
    },
    // 方法列表
    effects: {
        * qrcodeType({ payload }, { put, call, select }) {
            // console.log(payload)
            let { isNull } = payload
            const { data, success } = yield call(qrcodeType, {...payload })
            if (success) {
                if (isNull) {
                    yield put({ type: 'updateStore', payload: {...payload, zysqList: data } })
                } else {
                    yield put({ type: 'updateStore', payload: {...payload, channelType: data } })
                }

            }
        },

        * getAreaList({ payload }, { put, call, select }) {
            const { data, success } = yield call(queryAllAddress);
            if (success) {
                let areaList = []
                let arr = [data[0]]
                let attr = [data[data.length - 1]]
                data[0] = {
                    label: "北京",
                    value: "110100",
                    children: arr
                }
                data[data.length - 1] = {
                        label: "澳门",
                        value: "820000",
                        children: attr
                    }
                    //去掉第三级，
                areaList = makeAddress(data, 2)
                yield put({ type: 'updateStore', payload: { areaList } })
            }
        },

        * delBuilding({ payload }, { put, call, select }) {
            try {
                const { data, success } = yield call(delBuilding, payload);
                let defultState = yield select(state => state[tmpModule.namespace])
                if (success) {
                    message.success('删除成功')
                    message.success('删除成功', () => {
                        defultState.biz.refreshListDatas(true)
                    })
                } else {

                }
            } catch (e) {

            }
        },
        * shareImg({ payload }, { put, call, select }) {
            try {
                yield put({ type: 'updateStore', payload: { loading: true } })
                const { data, success } = yield call(shareImg, payload);
                if (success) {
                    console.log(data)
                    yield put({ type: 'updateStore', payload: { currentImg: data.fileUrl, loading: false, qrcodeCount: data.qrcodeCount, codeId: data.id, } })
                }
            } catch (e) {

            }
        },
        * count({ payload }, { put, call, select }) {

            try {
                let { codeId, channelId, currentItem } = yield select(state => state[tmpModule.namespace])
                    // console.log(channelId)
                const { data, success } = yield call(downloadQrcode, { id: codeId, channelType: channelId });
                if (success) {
                    // console.log(data)
                    // let imgSrcList = []

                    // imgSrcList.push(data.imgUrl)
                    // console.log(imgSrcLis)
                    // toZip(imgSrcList,'fileName');

                    download(data.imgUrl)
                    yield put({
                        type: 'shareImg',
                        payload: { productId: currentItem.productId }
                    })
                }
            } catch (e) {

            }
        },
        // *getBase64(img){
        //   let {url}=img
        //   var image = new Image();
        //   image.src = img.url;
        //   image.crossOrigin = '*';
        //   var deferred=$.Deferred();
        //   if(url){
        //     image.onload = ()=>{
        //       deferred.resolve(getBase64Image(image));//将base64传给done上传处理
        //     }
        //     // return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
        //   }

        //   function getBase64Image(img,width,height) {//width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
        //     debugger
        //     let canvas = document.createElement("canvas");
        //     canvas.width = width ? width : img.width;
        //     canvas.height = height ? height : img.height;

        //     let ctx = canvas.getContext("2d");
        //     ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        //     let ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
        //     // let dataURL = canvas.toDataURL("image/"+ext);
        //     let dataURL = canvas.toDataURL("image/"+ext);
        //     return dataURL;
        //   }

        // },
        //新增推荐楼盘
        *create({ payload }, { put, call, select }) {
            try{
            let {quer} = payload
            let obj = {
                resourceId: quer.resourceId,
                validityEndTime: quer.validityEndTime,
                validityStartTime: quer.validityStartTime,
                productTag: quer.productTag
            }
            const { success } = yield call(homeRecommendCreate, obj)
                if(success){
                    message.success('操作成功', () => {
                        defultState.biz.refreshListDatas(true)
                    })
                }
            }catch(e){
                console.error(e)
            }
        },
        * qrcodeCreate({ payload }, { put, call, select }) {
            try {
                let { codeId, channelId, currentItem } = yield select(state => state[tmpModule.namespace])
                const { data, success } = yield call(qrcodeCreate, { productId: currentItem.productId, ...payload });
                if (success) {
                    console.log(data)
                    yield put({
                        type: 'shareImg',
                        payload: { productId: currentItem.productId, channelType: payload.channelType }
                    })
                }
            } catch (e) {

            }
        }
    },



    // 存入状态机
    reducers: {
        updateStore(preState, action) {
            return {...preState, ...action.payload };
        }
    }
}

export default tmpModule